package com.easycoding.ums.context;

/***********************************************************************
*
* @model   公共Web上下文操作类
* @author  wjk 
* @version 1.0
* @purpose 业务系统利用此类操作Web上下文中登录、权限等相关信息   
*
***********************************************************************/

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;

import com.easycoding.framework.web.online.SessionUsers;
import com.easycoding.ums.security.shiro.SessionKey;
import com.easycoding.ums.system.bo.UserTicket;

public class WebUserContext {
	


	/**
	 * 判断用户是否已经登录
	 * 
	 * @return a boolean value 
	 */
	public static boolean userIsSignon() {
		return SecurityUtils.getSubject().isAuthenticated();
	}
	
	/**
	 *判断用户是否拥有web资源
	 * 
	 * @param httpServletRequest 当前Web请求
	 * @param resource_identity Web资源标识
	 * @return a boolean value 
	 */
	public static boolean userHasWebResource(String resource_identity) {
		UserTicket ticket = getUserTicket();
		if(ticket!=null) return ticket.hasWebResource(resource_identity);
			return false;
				
	}
	
	/**
	 *判断用户会话是否在线
	 * 
	 * @param httpServletRequest 当前Web请求
	 * @param resource_identity Web资源标识
	 * @return a boolean value
	 */
	public static boolean userSessionOnline(HttpServletRequest httpServletRequest) {
		if(userIsSignon()&&httpServletRequest.getSession()!=null){
			return userSessionOnline(httpServletRequest.getSession().getId());
		}
		return false;
	}
	
	/**
	 *判断用户会话是否在线
	 * 
	 * @return a boolean value
	 */
	public static boolean userSessionOnline(String session_id) {
		return !SessionUsers.getInstance().isSessionOverdue(session_id);
	}

	/**
	 *获取session中的验证票信息
	 * 
	 * @return a UserTicket value 
	 */
	public static UserTicket getUserTicket() {
		Object system_session = (Object) SecurityUtils.getSubject().getSession().getAttribute(SessionKey.USER);
		if (system_session != null && system_session instanceof UserTicket) {
			return (UserTicket) system_session;
		}
		else
			return null;
	}
	
	
	public static UserTicket getUserTicketContext() {
		 return getUserTicket();
	}
	
	/**
	 * 设置session中的验证票信息
	 * @param userTicket
	 * @return
	 */
	public static void setUserTicket(UserTicket userTicket) {
		SecurityUtils.getSubject().getSession().setAttribute(SessionKey.USER,userTicket);
	}
	
}
